package com.zephyr.monitorservice.controller;

import com.zephyr.monitorservice.entity.JvmMetric;
import com.zephyr.monitorservice.repository.JvmMetricRepository;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/metrics")
public class MetricsController {

    private final JvmMetricRepository repository;

    public MetricsController(JvmMetricRepository repository) {
        this.repository = repository;
    }

    // 获取最新一次采集的数据
    @GetMapping("/latest")
    public JvmMetric latest() {
        return repository.findAll()
                .stream()
                .reduce((first, second) -> second)
                .orElse(null);
    }

    // 获取最近 N 条数据
    @GetMapping("/history")
    public List<JvmMetric> history(@RequestParam(defaultValue = "20") int limit) {
        return repository.findAll()
                .stream()
                .sorted((a,b) -> b.getCollectedAt().compareTo(a.getCollectedAt()))
                .limit(limit)
                .toList();
    }
}
